<template>
  <div>
    <el-dialog
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      title="订单退款"
      width="750px"
      append-to-body
      @close="close"
    >
      <el-form
        v-if="detail"
        ref="form"
        v-loading="loading"
        :model="form"
        :rules="rules"
        size="small"
        label-width="150px"
      >
        <div v-for="(item,index) in detail.amounts" :key="index" class="flexRBC">
          <el-form-item v-if="item.type==='GOODS'" label="商品价格：">￥{{ item.amount / 100 }}</el-form-item>
          <el-form-item
            v-if="item.type==='DELIVERY'&&item.amount"
            label="订单运费："
          >￥{{ item.amount / 100 }}
          </el-form-item>
          <el-form-item v-if="item.type==='DISCOUNT'&&item.amount" label="订单优惠：">
            <span class="app-text-color-danger">-￥{{ item.amount / 100 }}</span>
          </el-form-item>
        </div>
        <div v-if="detail.subType==='DEPOSIT_PRESELL'&&detail.orderPresell">
          <el-form-item label="定金付款：">￥{{ detail.orderPresell.depositFee / 100 }}</el-form-item>
          <el-form-item label="尾款付款：">￥{{ detail.orderPresell.remainingFee / 100 }}</el-form-item>
        </div>
        <div v-else>
          <el-form-item label="订单付款：">￥{{
            detail.payInfo.payFee / 100
          }}（{{ paymentKeyOptions[detail.payInfo.paymentMethod] }}）
          </el-form-item>
        </div>
        <el-divider />
        <div v-if="detail.subType==='DEPOSIT_PRESELL'">
          <el-form-item label="定金退款金额：" prop="depositRefundFee">
            <el-input
              v-model.trim="form.depositRefundFee"
              :disabled="detail.orderPresell.depositFee - detail.depositRefundFeeTotal===0"
              placeholder="请输入金额"
              maxlength="10"
              class="w-200"
            >
              <template slot="append">元</template>
            </el-input>
            <span>已退￥{{
              detail.depositRefundFeeTotal / 100
            }}，剩余可退￥{{ (detail.orderPresell.depositFee - detail.depositRefundFeeTotal) / 100 }}</span>
          </el-form-item>
          <el-form-item label="尾款退款金额：" prop="refundFee">
            <el-input
              v-model.trim="form.refundFee"
              :disabled="detail.orderPresell.remainingFee - detail.refundFeeTotal===0"
              placeholder="请输入金额"
              maxlength="10"
              class="w-200"
            >
              <template slot="append">元</template>
            </el-input>
            <span>已退￥{{
              detail.refundFeeTotal / 100
            }}，剩余可退￥{{ (detail.orderPresell.remainingFee - detail.refundFeeTotal) / 100 }}</span>
          </el-form-item>
        </div>
        <div v-else>
          <el-form-item label="退款金额：" prop="refundFee">
            <el-input v-model.trim="form.refundFee" placeholder="请输入金额" maxlength="10" class="w-200">
              <template slot="append">元</template>
            </el-input>
            <span>已退￥{{
              $math.div(detail.refundAmt , 100)
            }}，剩余可退￥{{ $math.div(detail.canRefAmt , 100) }}</span>
          </el-form-item>
        </div>

        <el-form-item label="退款备注：" prop="reason">
          <el-input
            v-model="form.reason"
            :autosize="{ minRows: 2, maxRows: 10}"
            type="textarea"
            placeholder="请输入备注"
            show-word-limit
            maxlength="200"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <div class="flexCCC">
          <el-button
            :disabled="loading"
            size="large"
            round
            type="primary"
            class="btn-submit"
            @click="showPwdModal"
          >申请退款
          </el-button>
          <el-button :disabled="loading" size="text" round @click="hide">取 消</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 验证登录密码 -->
    <el-dialog
      title="验证身份"
      :visible.sync="pwdVisible"
      append-to-body
      width="40%"
    >
      <el-form ref="form" :model="refundForm" label-width="80px">
        <el-form-item label="登录密码">
          <el-input v-model="refundForm.pwd" size="small" placeholder="请输入登录密码" />
          <span>*验证登录密码成功后会直接发起退款</span>
        </el-form-item>
        <el-form-item>
          <el-button size="small" @click="pwdVisible = false">取消</el-button>
          <el-button type="primary" size="small" @click="validPwd">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import { orderRefund } from '@/views/wxaMallModule/api/order'
import { chkLoginPwd } from '@/api/payCenter'
import { validateCustomTwoDecimal } from '@/utils/validate'
import { mapGetters } from 'vuex'
import confirmMessage from '@/components/ConfirmMessage/index'

export default {
  data() {
    const validateDepositRefundFee = (rule, value, callback) => {
      if ((this.detail.orderPresell.depositFee - this.detail.depositRefundFeeTotal) === 0) {
        callback()
      } else if (this.$isNull(value) && this.form.refundFee) {
        callback()
      } else if (this.$isNull(value)) {
        callback(new Error('请输入金额'))
      } else if (!validateCustomTwoDecimal(value, 10)) {
        callback(new Error('请输入正整数，正小数（小数位不超过2位）'))
      } else if (
        this.$math.mul(value, 100, 0) -
        (this.detail.orderPresell.depositFee - this.detail.depositRefundFeeTotal) >
        0
      ) {
        callback(
          new Error(
            `最大可退金额为 ${
              (this.detail.orderPresell.depositFee - this.detail.depositRefundFeeTotal) / 100
            }`
          )
        )
      } else {
        this.$refs.form.clearValidate(['refundFee'])
        callback()
      }
    }

    const validateRefundFee = (rule, value, callback) => {
      // 定金模式
      if (this.detail.subType === 'DEPOSIT_PRESELL') {
        if ((this.detail.orderPresell.remainingFee - this.detail.refundFeeTotal) === 0) {
          callback()
        } else if (this.$isNull(value) && this.form.depositRefundFee) {
          callback()
        } else if (this.$isNull(value)) {
          callback(new Error('请输入金额'))
        } else if (!validateCustomTwoDecimal(value, 10)) {
          callback(new Error('请输入正整数，正小数（小数位不超过2位）'))
        } else if (
          this.$math.mul(value, 100, 0) -
          (this.detail.orderPresell.remainingFee - this.detail.refundFeeTotal) >
          0
        ) {
          callback(
            new Error(
              `最大可退金额为 ${
                (this.detail.orderPresell.remainingFee - this.detail.refundFeeTotal) / 100
              }`
            )
          )
        } else {
          this.$refs.form.clearValidate(['depositRefundFee'])
          callback()
        }
      } else {
        if (this.$isNull(value)) {
          callback(new Error('请输入金额）'))
        } else if (!validateCustomTwoDecimal(value, 10)) {
          callback(new Error('请输入正整数，正小数（小数位不超过2位）'))
        } else if (
          this.$math.mul(value, 100, 0) -
          (this.detail.payInfo.payFee - this.detail.refundFeeTotal) >
          0
        ) {
          callback(
            new Error(
              `最大可退金额为 ${
                (this.detail.payInfo.payFee - this.detail.refundFeeTotal) / 100
              }`
            )
          )
        } else {
          callback()
        }
      }
    }
    return {
      // 校验字段
      rules: {
        depositRefundFee: [
          {
            required: true,
            validator: validateDepositRefundFee,
            trigger: ['blur', 'change']
          }
        ],
        refundFee: [
          {
            required: true,
            validator: validateRefundFee,
            trigger: ['blur', 'change']
          }
        ]
      },
      // 配置
      resolve: null,
      reject: null,
      // 状态
      loading: false,
      dialogVisible: null,
      pwdVisible: false,
      // 数据
      refundForm: {
        pwd: ''
      },
      detail: null,
      form: {
        orderNo: null,
        depositRefundFee: null,
        refundFee: null,
        reason: null
      }
    }
  },
  computed: {
    ...mapGetters(['paymentKeyOptions'])
  },
  methods: {
    /**
     * 弹框相关
     */
    open({ detail }) {
      this.detail = detail
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true
    },

    close() {
      this.form = {
        orderNo: null,
        depositRefundFee: null,
        refundFee: null,
        reason: null
      }
      this.loading = false
      this.$refs.form.resetFields()
    },

    hide() {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
    },

    /**
     * 数据组
     */

    /**
     * 按钮组
     */
    showPwdModal() {
      this.$refs.form.validate((valid) => {
        this.detail.fapiaoSts && confirmMessage({ title: '退款发票自动冲红提示', center: true })
          .then(() => {
            if (valid) {
              this.pwdVisible = true
            }
          })
          .catch(() => {
            console.log('我是取消')
          })
        !this.detail.fapiaoSts && valid && (this.pwdVisible = true)
      })
    },
    validPwd() {
      const { pwd } = this.refundForm
      if (!pwd) {
        this.$message.error('请输入登录密码')
        return
      }
      // 校验登录密码
      chkLoginPwd({ password: pwd }).then(res => {
        console.log('res', res)
        this.pwdVisible = false
        this.submit()
      })
    },
    // 确 定
    submit() {
      const params = Object.assign({}, this.form)
      if (this.$isNull(params.depositRefundFee) && this.$isNull(params.refundFee)) {
        this.$message.warning('请填写退款金额')
        return
      }
      params.orderNo = this.detail.orderNo
      params.depositRefundFee = params.depositRefundFee ? this.$math.mul(params.depositRefundFee, 100, 0) : null
      params.refundFee = params.refundFee ? this.$math.mul(params.refundFee, 100, 0) : null
      this.loading = true
      orderRefund(params)
        .then((res) => {
          this.$notify({
            title: '成功',
            message: '已提交退款申请',
            type: 'success',
            duration: 2000,
            offset: 40
          })
          this.resolve && this.resolve()
          this.hide()
        })
        .catch((err) => {
        })
        .finally(() => {
          this.loading = false
        })
    }

    /**
     * 状态组
     */

    /**
     * 方法组
     */
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.w-400 {
  width: 400px;
  display: block;
  margin: 0 auto;
}

.w-200 {
  width: 200px;
}

.btn-submit {
  margin-bottom: 20px;
}
</style>
